#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :price_warning_setting_page.py
# Time  :2025/3/31 15:09
# Email :fortunatedong@163.com
# Author:by Adonli
import time
import streamlit as st
import pandas as pd
import toml
from apscheduler.schedulers.background import BackgroundScheduler
from config import Header_space
Header_space()

st.subheader("价格预警设置", divider=True)
col1,col2 = st.columns([5,3])
with open("settings/configs.toml", "r", encoding="utf-8") as f:
    cfg = toml.load(f)

task_list = cfg["TASK"]["TaskList"]
task_name = cfg["TASK"]["TaskName"]
task_time = cfg["TASK"]["TaskTime"]
interval_length = cfg["TASK"]["IntervalLength"]
interval_list = cfg["TASK"]["IntervalList"]
interval_length_index = interval_list.index(interval_length)
dingtalk_recipient = cfg["TASK"]["DingtalkRecipient"]
# print(dingtalk_recipient)
@st.dialog("定时任务信息")
def vote(item):
    st.markdown(
        f"## :rainbow[执行任务名称：] :violet[{item['task_name']}]\n"
        f"## :rainbow[每天运行时间：] :violet[{item['task_time']}]\n"
        f"## :rainbow[运行间隔时间：] :violet[{item['interval_length']}]\n"
        f"## :rainbow[钉钉通知人：]\n :violet[{item['dingtalk_recipient']}]"
    )
    if st.button("确定"):
        cfg['TASK']['TaskName'] = item['task_name']
        cfg['TASK']['TaskTime'] = str(item['task_time'])
        cfg['TASK']['IntervalLength'] = item['interval_length']
        cfg['TASK']['DingtalkRecipient'] = item['dingtalk_recipient']

        with open('settings/configs.toml', 'w', encoding="utf-8") as f:
            toml.dump(cfg, f)
        st.success('成功保存！', icon="✅")
        time.sleep(1)

        st.rerun()


with col1:
    task_name = st.selectbox("选择定时任务:",task_list)
    task_time = st.time_input("请选择时间：每天何时开始定时任务（遍历每个SKU）?", value=pd.to_datetime(task_time))
    interval_length = st.selectbox(
        "请选择间隔时长：间隔几小时进行下一次遍历",
        interval_list,
        index = interval_length_index,
    )
    dingtalk_recipient = st.text_area(
        "请输入钉钉通知人手机号([159xxxxxx])：通知多人需用逗号隔开，如（[138xxxxxxx,156xxxxxx]）",
        f"{dingtalk_recipient}",
    )
    # dingtalk_recipient = list(set(dingtalk_recipient.extend(iphone_number)))

    item = {
        "task_name": task_name,
        "task_time": task_time,
        "interval_length": interval_length,
        "dingtalk_recipient": dingtalk_recipient,
    }
    col1_col1, col1_col2 = st.columns([4, 1])
    with col1_col2:
        if st.button("保存",type="primary"):
            vote(item)
with col2:
    task_status = cfg["TASK"]["TaskStatus"]
    item["task_status"] = task_status
    col2_col1, col2_col2 = st.columns([1, 8])
    with col2_col2:
        container = st.container(border=True)
        container.header("启动任务",divider="gray")
        on = container.toggle(f"## :rainbow[{item['task_name']}-每天{item['task_time']}开始-时长间隔{item['interval_length']}]",
                              value=task_status,)
        task_status = item['task_status']
        duration = item['interval_length'].replace("小时", "h")
        scheduler = BackgroundScheduler()
        if task_status:
            if not on:
                cfg['TASK']['TaskStatus'] = on
                with open('settings/configs.toml', 'w', encoding="utf-8") as f:
                    toml.dump(cfg, f)
                # scheduled_task = ScheduledTask(task=job(), start_time=item['task_time'], Loop=True, duration=duration,
                #                                end_time="22:00",
                #                                cycle="day")
                # scheduled_task.stop()
                st.rerun()
        else:
            if on:
                cfg['TASK']['TaskStatus'] = on
                with open('settings/configs.toml', 'w', encoding="utf-8") as f:
                    toml.dump(cfg, f)
                # scheduled_task = ScheduledTask(task=job(), start_time=item['task_time'], Loop=True, duration=duration,
                #                                end_time="22:00",
                #                                cycle="day")
                # scheduled_task.start()
                # scheduler.add_job(job, 'cron', hour=11, minute=4)
                # scheduler.start()
                st.rerun()







